package com.dragon.sdgp.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.sdgp.common.R;
import com.dragon.sdgp.entity.Lexicon;
import com.dragon.sdgp.entity.LexiconCollection;
import com.dragon.sdgp.entity.LexiconItem;
import com.dragon.sdgp.entity.SysUser;
import com.dragon.sdgp.entity.dto.LexiconDto;
import com.dragon.sdgp.entity.vo.LexiconVo;
import com.dragon.sdgp.mapper.LexiconMapper;
import com.dragon.sdgp.service.LexiconCollectionService;
import com.dragon.sdgp.service.LexiconItemService;
import com.dragon.sdgp.service.LexiconService;
import com.dragon.sdgp.service.SysUserService;
import com.dragon.sdgp.util.CommonUtil;
import com.dragon.sdgp.util.JWTUtil;
import com.dragon.sdgp.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @AUTHOR : Dragon_Yang
 * @File : LexiconServiceImpl
 * @DESCRIPTION :
 * @DATE : 2023/3/17 19:37
 */
@Service
public class LexiconServiceImpl extends ServiceImpl<LexiconMapper, Lexicon> implements LexiconService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LexiconItemService lexiconItemService;

    @Autowired
    private LexiconCollectionService lexiconCollectionService;

    /**
     * 获取所有词库，带分页
     * @param token
     * @param key   搜索关键字
     * @param page  页码，默认一页10条数据
     * @return
     */
    @Override
    public R getLexiconList(String token, String key, Integer page) {
        SysUser user = null;
        if(!StringUtil.isEmpty(token)){
            try {
                String account = JWTUtil.decode(token);
                user = sysUserService.getUserByEMailOrPhone(account);
            }catch (Exception e) {
                // 不用处理异常
            }
        }
        HashMap<Integer, Integer> collectionMap = new HashMap<>();
        if(user != null){
            //TODO 优化：不要查全部，查分页的部分
            List<Integer> collect = getCollectionLexiconIdByUser(user);
            collect.forEach(id -> collectionMap.put(id, 1));
        }
        QueryWrapper<Lexicon> lexiconQueryWrapper = new QueryWrapper<>();
        lexiconQueryWrapper.eq("is_share", 1);
        if(!StringUtil.isEmpty(key)){
            lexiconQueryWrapper.likeRight("title", key)
                    .likeRight("info", key);
        }
        int count = count(lexiconQueryWrapper);
        List<LexiconVo> list = list(lexiconQueryWrapper.orderByDesc("update_time").last("limit " + (page - 1) * 10 + ", 10")).stream().map(lexicon -> {
            LexiconVo lexiconVo = new LexiconVo();
            lexiconVo.setId(lexicon.getId());
            lexiconVo.setTitle(lexicon.getTitle());
            lexiconVo.setInfo(lexicon.getInfo());
            lexiconVo.setAuthor(lexicon.getAuthor());
            lexiconVo.setCreateTime(lexicon.getCreateTime());
            lexiconVo.setIsCollection(0);
            lexiconVo.setIsShare(0);
            if(collectionMap.containsKey(lexicon.getId())){
                lexiconVo.setIsCollection(1);
                lexiconVo.setIsShare(1);
            }
            return lexiconVo;
        }).collect(Collectors.toList());
        return R.success(200, MapUtil.builder()
                .put("count", count)
                .put("list", list).map());
    }

    /**
     * 添加词库
     * @param lexiconDto
     * @param token
     * @return
     */
    @Override
    public R addLexicon(LexiconDto lexiconDto, String token){
        SysUser user = sysUserService.getUserByEMailOrPhone(JWTUtil.decode(token));
        if(user == null) return R.fail(400, "登录过期，请重新登录！");
        Lexicon lexicon = new Lexicon();
        lexicon.setTitle(lexiconDto.getTitle());
        lexicon.setInfo(lexiconDto.getInfo());
        lexicon.setUserId(user.getId());
        lexicon.setAuthor(user.getUsername());
        boolean save = save(lexicon);
        if (!save) return R.fail(400, "添加失败！");
        LexiconItem lexiconItem = new LexiconItem();
        lexiconItem.setLexiconId(lexicon.getId());
        lexiconItem.setContent(lexiconDto.getWords());
        boolean saveItem = lexiconItemService.save(lexiconItem);
        if(!saveItem) return R.fail(400, "添加失败！");
        return R.success(200, null);
    }

    /**
     * 获取我的词库
     * @param token
     * @return
     */
    @Override
    public R getLexiconListByAccount(String token) {
        SysUser user = sysUserService.getUserByEMailOrPhone(JWTUtil.decode(token));
        if(user == null) return R.fail(400, "登录过期，请重新登录！");
        QueryWrapper<Lexicon> lexiconQueryWrapper = new QueryWrapper<>();
        lexiconQueryWrapper.eq("user_id", user.getId());
        return R.success(200, list(lexiconQueryWrapper));
    }

    /**
     * 获取我的收藏
     * @param token
     * @return
     */
    @Override
    public R getCollectionList(String token){
        SysUser user = sysUserService.getUserByEMailOrPhone(JWTUtil.decode(token));
        if(user == null) return R.fail(400, "登录过期，请重新登录！");
        List<Integer> collect = getCollectionLexiconIdByUser(user);
        if(collect == null || collect.size() == 0) return R.success(200, new ArrayList<>());
        QueryWrapper<Lexicon> lexiconQueryWrapper = new QueryWrapper<>();
        lexiconQueryWrapper.eq("is_share", 1)
                .in("id", collect);
        return R.success(200, list(lexiconQueryWrapper));
    }

    /**
     * 共享或取消
     * @param id
     * @return
     */
    @Override
    public R shareOrCancel(Integer id) {
        Lexicon lexicon = getById(id);
        if(lexicon == null) R.fail(400, "词库不存在");
        lexicon.setIsShare((lexicon.getIsShare() == 0 ? 1 : 0));
        updateById(lexicon);
        return R.success(200, null);
    }

    /**
     * 收藏或取消
     * @param id
     * @param token
     * @return
     */
    @Override
    public R collectionOrCancel(Integer id, String token) {
        SysUser user = sysUserService.getUserByEMailOrPhone(JWTUtil.decode(token));
        if(user == null) return R.fail(400, "登录过期，请重新登录！");
        QueryWrapper<LexiconCollection> lexiconCollectionQueryWrapper = new QueryWrapper<>();
        lexiconCollectionQueryWrapper.eq("user_id", user.getId())
                .eq("lexicon_id", id);
        LexiconCollection one = lexiconCollectionService.getOne(lexiconCollectionQueryWrapper);
        if(one == null){
            one = new LexiconCollection();
            one.setUserId(user.getId());
            one.setLexiconId(id);
        }else {
            one.setIsCollection((one.getIsCollection() == 0 ? 1 : 0));
        }
        boolean b = lexiconCollectionService.saveOrUpdate(one);
        if(!b) R.fail(400, "词库不存在");
        return R.success(200, null);
    }

    /**
     * 获取词库的词条
     * @param id
     * @return
     */
    @Override
    public R getLexiconItem(Integer id) {
        LexiconItem lexiconItem = lexiconItemService.getOne(new QueryWrapper<LexiconItem>().eq("lexicon_id", id));
        if(lexiconItem == null) R.fail(400, "词库不存在");
        return R.success(200, lexiconItem.getContent().split("\n"));
    }

    private List<Integer> getCollectionLexiconIdByUser(SysUser sysUser){
        QueryWrapper<LexiconCollection> lexiconCollectionQueryWrapper = new QueryWrapper<>();
        lexiconCollectionQueryWrapper.eq("user_id", sysUser.getId())
                .eq("is_collection", 1);
        ArrayList<Integer> collect = lexiconCollectionService.list(lexiconCollectionQueryWrapper).stream()
                .map(lexiconCollection -> lexiconCollection.getLexiconId()).collect(Collectors.toCollection(ArrayList::new));
        return collect;
    }

}
